#pragma once
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include "../Sock/Socket.hpp"
#include "../Sock/errno.hpp"
#include "../Sock/Logmessage.hpp"

namespace echoClient
{
    class Client
    {
        std::string ip_;
        uint16_t  port_;
        int sockfd_;
    public:
        Client(const std::string& ip,const uint16_t port)
            :ip_(ip),port_(port),sockfd_(-1)
        {}

        void init()
        {
            sockfd_=Socket::CreateSock();
        }

        void run()
        {
            if(Socket::Connect(sockfd_,ip_,port_)!=0)
            {
                logMessage(WARNING,"connect err...");
            }

            serverIO();
        }
        ~Client()
        {
            if(sockfd_>=0)
                close(sockfd_);
        }
    private:
        void serverIO()
        {
            std::string msg;
            while (true)
            {
                std::cout << "Enter# ";
                getline(std::cin, msg);
                write(sockfd_, msg.c_str(), msg.size());

                char buffer [1024];
                ssize_t n=read(sockfd_,buffer,sizeof(buffer)-1);
                if (n>0)
                {
                    buffer[n]=0;
                    std::cout<<"Server处理后为# "<<buffer<<std::endl;
                }
                else
                {
                    break;
                }
            }
        }      
    };
}